var cur={
	constant:{
		ue_id:1,
		_cityCode:0,
		_countyCode:0,
		_streetCode:0,
	}
};
;$(function () {
    var serverIdArr =[];
    var id = $("#id").val();
    if(id==null||id==""){
    	 getCityList("421000","421000","421002","421002001000");
    	upload(serverIdArr);
    }else{
    	getInfo(id, serverIdArr);
    }
    submitForm();
})
var tale = new $.tale();//弹框
function upload(serverIdArr) {
    $("#dropzone").dropzone({
        paramName: "file",
        url: "/file/upload",
        addRemoveLinks: true,
        dictRemoveLinks: "x",
//        uploadMultiple: true,
        maxFilesize: 10,
        init: function () {
            this.on("success", function (file, msg) {
                file.serverId = msg.message;
                serverIdArr=msg.message;
            	$("#image_files").val(serverIdArr);
            });
            this.on('error', function (files, response) {
                //文件上传失败后的操作
                console.log(files, response);
            });
            //删除图片的事件，当上传的图片为空时，使上传按钮不可用状态
            this.on("removedfile", function (file) {
            	serverIdArr.splice($.inArray(file.serverId,serverIdArr),1);
            	$("#image_files").val(serverIdArr);
            });
        }
    });
}


function getInfo(id, serverIdArr) {
    $.ajax({
        url: ctxPath+"/agency/remove/findById/" + id,
        type: 'GET',
        success: function (d) {
            var success = d.success;
            if (success == true) {
                var data = d.data;
                umbinding.bind(data);
                 cur.constant._countyCode=data.cityCode;
                getCityList(data.cityCode,data.countyCode,data.streetCode);
                if(data.scheduleList!=null){
                	showSchedule(data.scheduleList);
                }
                serverIdArr.push(data.fileIds);
                $("#image_files").val(serverIdArr);
                var myDropzone = new Dropzone("#dropzone", {
                    paramName: "file",
                    url: ctxPath+"/file/upload",
                    addRemoveLinks: true,
                    dictRemoveLinks: "x",
//        	        uploadMultiple: true,
                    maxFiles: 3,
                    maxFilesize: 10,
                    init: function () {
                        this.on("success", function (file, msg) {
                        	 file.serverId = msg.message;
                             serverIdArr.push(msg.message);
                             $("#image_files").val(serverIdArr);
                        });
                        this.on('error', function (files, response) {
                        });
                        //删除图片的事件，当上传的图片为空时，使上传按钮不可用状态
                        this.on("removedfile", function (file) {
                        	 serverIdArr.splice($.inArray(file.serverId, serverIdArr), 1);
                             $("#image_files").val(serverIdArr);
                        });
                    }
                });
                if (data.files != null) {
                    for (var i = 0; i < data.files.length; i++) {
                        var size = data.files[i].size * 1024;
                        var mockFile = {
                            name: data.files[i].srcname,
                            accepted: true,
                            size: size, //图片尺寸
                            height: "70%",
                            width: "70%",
                            type: '.jpg,.png,.gif'//图片文件类型
                        };
                        myDropzone.emit("addedfile", mockFile);
                        myDropzone.emit("thumbnail", mockFile, ctxPath+"/file/showImage/" + data.files[i].id);
                        myDropzone.emit("complete", mockFile);
                    }
                }
            }
        },
        error: function () {
        	var myDropzone = new Dropzone("#dropzone", {
                paramName: "file",
                url: "/file/upload",
                addRemoveLinks: true,
                dictRemoveLinks: "x",
//        	        uploadMultiple: true,
                maxFiles: 3,
                maxFilesize: 10,
                init: function () {
                    this.on("success", function (file, msg) {
                        file.serverId = msg.message;
                        serverIdArr.push(msg.message);
                        $("#image_files").val(serverIdArr);
                    });
                    this.on('error', function (files, response) {
                    });
                    //删除图片的事件，当上传的图片为空时，使上传按钮不可用状态
                    this.on("removedfile", function (file) {
                        serverIdArr.splice($.inArray(file.serverId, serverIdArr), 1);
                        $("#image_files").val(serverIdArr);
                    });
                }
            });
        }

    });
}

/**
 * 创建进度
 * @param data
 * @returns
 */
function showSchedule(data){
	for(var i=0;i<data.length;i++){
		if(i==0){
			var date =data[0].reportdate;
			var content =data[0].content;
		  $("#scheduleList_0").val(date);
		  ue.ready(function () {//监听编辑器实例化完成的事件
	           if (content!= null) {
	               ue.setContent(content);
	           }
	       });	
		}else{
			add_ue2(data[i]);
		}
  }
}

function submitForm() {
    $("#global-form").validator({
        rules: {
            mobile: function (element, params) {
                var tel = /^(0[0-9]{2,3}\-)([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;
                return tel.test(element.value) || '请检查电话号码';
            },
        },
        fields: {
            title: {
                rule: "required;",
                msg: {
                    required: "必填!"
                }
            },
            type: {
                rule: "required;",
                msg: {
                    required: "必填!"
                }
            },
        },
        invalid: function (form, errors) {
            console.log(errors);
            $(".btn-submit").removeAttr("style");
        },
        //验证成功
        valid: function (form) {
            saveInfo();
        },
    });
}

function saveInfo() {
    var json = $("#global-form").serializeFormJSON();
    console.log(json);
    var id = $("#id").val();
    var url = ctxPath+"/agency/remove/saveInfo";
    if (id != '' && id != null) {
        url = ctxPath+"/agency/remove/updateInfo";
    }
    $.ajax({
        url: url,
        type: 'POST',
        data: json,
        success: function (d) {
            var success = d.success;
            if (success) {
                tale.alertOk({
                    text: '保存成功',
                    then: function () {
                        setTimeout(function () {
                            window.location.href = ctxPath+'/agency/remove/list';
                        }, 500);
                    }
                });
            } else {
                tale.alertError(result.message || '保存失败');
            }
        }
    });
}



function add_ue(){
	var id="container_"+cur.constant.ue_id;
	var d ="scheduleList_"+cur.constant.ue_id;
	var div='<div id="div_'+cur.constant.ue_id+'"><div class="form-group">'
	      +'<label class="col-sm-1 control-label"></label>'
	      +'<div class="col-md-4">'
	      +'<input type="text" class="form-control" id="'+d+'"  name="scheduleList['+cur.constant.ue_id+'].reportdate" placeholder="拆迁进度" required="required" aria-required="true"/>' 
	      +'</div> <a class="btn btn-danger" href="javascript:void(0)" onclick="removeDiv('+cur.constant.ue_id+')" title="删除">删除</a>'
	      +'</div>'     
	      +'<div class="form-group">'
	      +'<label class="col-sm-1 control-label"></label>'
	      +'<div class="col-md-8">'
	      +'<script type="text/plain" id="'+id+'" name="scheduleList['+cur.constant.ue_id+'].content" style="width:650px;height:500px;"></script>'
	      +'</div><div>'
	$("#schedule_result").append(div);
	UE.getEditor(id);
	cur.constant.ue_id=cur.constant.ue_id+1;
	 $('#'+d).datetimepicker({
         format: 'yyyy-mm-dd', 
         minView: "month", //选择日期后，不会再跳转去选择时分秒 
         language: 'zh-CN',
         autoclose: true,
     }).on('change',function(){
	 		$(this).attr("class","form-control");
	 		$(this).siblings('span').html('');
		});
}

function add_ue2(data){
	var id="container_"+cur.constant.ue_id;
	var d ="scheduleList_"+cur.constant.ue_id;
	var div='<div id="div_'+cur.constant.ue_id+'"><div class="form-group">'
	+'<label class="col-sm-1 control-label"></label>'
	+'<div class="col-md-4">'
	+'<input type="text" class="form-control" id="'+d+'"  name="scheduleList['+cur.constant.ue_id+'].reportdate" placeholder="拆迁进度" value="'+data.reportdate+'" required="required" aria-required="true"/>' 
	+'</div> <a class="btn btn-danger" href="javascript:void(0)" onclick="removeDiv('+cur.constant.ue_id+')" title="删除">删除</a>'
	+'</div>'     
	+'<div class="form-group">'
	+'<label class="col-sm-1 control-label"></label>'
	+'<div class="col-md-8">'
	+'<script type="text/plain" id="'+id+'" name="scheduleList['+cur.constant.ue_id+'].content" style="width:650px;height:500px;"></script>'
	+'</div><div>'
	$("#schedule_result").append(div);
	console.log("id:  "+id);
	var temp = UE.getEditor(id);
	   temp.ready(function () {//监听编辑器实例化完成的事件
           if (data.content!= null) {
        	   temp.setContent(data.content);
      }
     });
	cur.constant.ue_id=cur.constant.ue_id+1;
	$('#'+d).datetimepicker({
		format: 'yyyy-mm-dd', 
		minView: "month", //选择日期后，不会再跳转去选择时分秒 
		language: 'zh-CN',
		autoclose: true,
	}).on('change',function(){
		$(this).attr("class","form-control");
		$(this).siblings('span').html('');
	});
}

function removeDiv(id){
	$("#div_"+id).empty();
}


function createMap(){
	 $("#mapModal").modal("show");
	setTimeout(function() {		//添加延时加载。解决问题
		var map = new BMap.Map("map_main");
		var myCity = new BMap.LocalCity();
		myCity.get(function(res){
			map.centerAndZoom(res.center,res.level); 
			var old_map = $('#map').val();		//如果已设置过
			if(old_map.length > '5'){			//打开的时候显示已设置的
				$("#map_txt").val(old_map);		
				var oldMap = old_map.split(",");
				var point = new BMap.Point(oldMap[0],oldMap[1]);    
				var marker = new BMap.Marker(point);        // 创建标注    
				map.clearOverlays();
				map.addOverlay(marker);
			}
			map.addEventListener("click", function(e){
				var lng_lat = e.point.lng+','+e.point.lat;
				$("#map_txt").val(lng_lat);					//加入到设置框
				var point = new BMap.Point(e.point.lng,e.point.lat);    
				var marker = new BMap.Marker(point);        // 创建标注    
				map.clearOverlays();
				map.addOverlay(marker);
			});
		});
	},300);
}

//设置经纬度
function setMapValue(){
if($("#map_txt").val()==""){ alert('你还没选择相应的坐标点^_^哦'); return false; }
$("#map").val($("#map_txt").val());
$('#mapModal').modal('hide')
}